import prisma from "../prisma/prismaClient.js";
import { nanoid } from "nanoid";
// 获取所有用户
const getAllUsers = () => prisma.user.findMany();

const getTenUsers = async () => {
  return await prisma.user.findMany({
    orderBy: {
      lastLogin: 'desc'
    },
    take: 10,
  });
};

//获取总数和今日新增数
const getUserIncreaseInfo = async () => {
  const todayStart = new Date();
  todayStart.setHours(0, 0, 0, 0);

  const total = await prisma.user.count()
  const today = await prisma.user.count({
    where: {
      createdAt: {
        gte: todayStart,
      }
    }
  })
  return {
    total,
    today
  }
}

//获取最近n天的用户数
const getRecentDaysUsers = async (days = 7) => {
  const results = [];
  const today = new Date();

  // 确保只查询days天（包括今天）
  for (let i = days - 1; i >= 0; i--) {
    const date = new Date(today);
    date.setDate(date.getDate() - i);
    date.setHours(23, 59, 59, 999);

    const total = await prisma.user.count({
      where: {
        createdAt: {
          lte: date
        }
      }
    });

    const dateStr = date.toLocaleDateString('en-CA'); // YYYY-MM-DD格式

    results.push({
      date: dateStr,
      total
    });
  }

  return results;
};
// 获取单个用户
const getUserById = (id) => prisma.user.findUnique({ where: { id } });

// 获取单个用户
const getUserByUsername = (username) =>
  prisma.user.findUnique({ where: { username } });

// 创建新用户
const createUser = (username, password, storage) =>
  prisma.user.create({ data: { id: nanoid(6), username, password, storage } });

// 更新用户
const updateUser = (id, updates) =>
  prisma.user.update({ where: { id }, data: updates });

// 删除用户
const deleteUser = (id) => prisma.user.delete({ where: { id } });

//使用
const increaseUsed = async (userId, size) => {
  let increment = parseInt(size);
  const user = await getUserById(userId);
  if (Number(user.used) + increment > Number(user.storage)) {
    console.error('用户空间异常，使用了超出的空间', user, decrement)
    return prisma.user.update({
      where: { id: userId },
      data: { used: Number(user.storage) },
    })
  }
  return prisma.user.update({
    where: { id: userId },
    data: {
      used: { increment },
    },
  });
};

//释放空间
const decreaseUsed = async (userId, size) => {
  let decrement = parseInt(size);
  const user = await getUserById(userId);
  if (Number(user.used) < decrement) {
    console.error('用户空间异常，释放了超出的空间', user, decrement)
    return prisma.user.update({
      where: { id: userId },
      data: { used: 0 },
    })
  }

  return prisma.user.update({
    where: { id: userId },
    data: {
      used: { decrement },
    },
  });
}

export default {
  getAllUsers,
  getUserById,
  getUserByUsername,
  createUser,
  updateUser,
  deleteUser,
  increaseUsed,
  decreaseUsed,
  getUserIncreaseInfo,
  getRecentDaysUsers,
  getTenUsers
};
